<template>
  <div v-load="init" ref="chartDom" class="charts">
    
  </div>
</template>

<script setup>
import * as echarts from 'echarts'
import { onMounted, onUnmounted, watch, ref, markRaw } from 'vue';

const props = defineProps({
  option: {
    type: Object,
    require: true
  }
})

const myChart = ref()

const chartDom = ref(null)

const reload = () => {
  if (chartDom.value.hasAttribute('_echarts_instance_')) {
    chartDom.value.removeAttribute('_echarts_instance_')
  }
  myChart.value = markRaw(echarts.init(chartDom.value))
  props.option && myChart.value.setOption(props.option)
}

const handleResize = () => {
  myChart.value.resize()
}


const init = () => {
  if (!chartDom.value) {
    return
  }
  reload()
  window.addEventListener('resize', handleResize)
}

watch(() => props.option, () => {
  reload()
}, {
  deep: true,
})

onMounted(() => {
  // 不懒加载时需解开注释
  init()
})

onUnmounted(() => {
  myChart.value.clear()
  window.removeEventListener('resize', handleResize)
})

let observer
const vLoad = {
  mounted: (el, binding) => {
    console.log(el, binding)
    observer = new IntersectionObserver(([{isIntersecting}]) => {
      // console.log('触发了', isIntersecting)
      if (isIntersecting) {
        // 懒加载中执行init方法
        binding.value && binding.value()
        observer.unobserve(el)
      }
    })
    observer.observe(el)
  },
  onUnmounted: (el) => {
    observer.unobserve(el)
  }
}
</script>

<style>
.charts {
  height: 100%;
  width: 100%;
}
</style>